<?php

namespace App\Kuafu\Mybank\Service\CalcBrokerage;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Mybank\Model\MybankBillRecordModel;
use App\Kuafu\Mybank\Model\MybankEntryModel;
use App\Kuafu\Mybank\Model\MybankShopBindModel;
use App\Kuafu\Mybank\Service\MybankBrokerageService;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Resources\B\ShopSimpleResource;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Scope\ShopScope;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class MybankCalcOrderBrokerageService extends MybankCalcBrokerageService
{

    protected $orderInfo;

    /**
     * 堂食计算佣金
     */
    public function calcBrokerage()
    {
        $this->orderInfo = OrderSplitModel::suffix($this->shopId)
                                          ->select(['orderId', 'realPayPrice', 'refundMoney'])
                                          ->where('orderId', (int)$this->orderId)
                                          ->first();

        if (empty($this->orderInfo)) {
            return;
        }

        // 判断是否存在退款, 如果存在退款, 重新计算门店历史
        if ($this->orderInfo['refundMoney'] > 0) {
//            MybankBrokerageService::forgetShopAllIncomeMonthCache($this->shopId);
            MybankBrokerageService::refreshShopAllIncomeMonthCache($this->shopId);
        }

        // 获取总实收
        $sumPayPriceResult = MybankBrokerageService::getShopAllIncomeMonthWithCache($this->shopId);
        $sumPayPrice       = $sumPayPriceResult['sumPrice'];
        $isNew             = $sumPayPriceResult['isNew'];

        $price   = $this->orderInfo->realPayPrice;
        $percent = MybankBrokerageService::getPercentByDefaultConfig($this->shopId, $sumPayPrice);

        $brokerage = bcmul($price, $percent);

        $this->brokerage      = $brokerage;
        $this->brokeragePer   = $percent * 100 . '%';
        $this->divisionBillId = 0;

        Log::channel('mybank')->info('calcBrokerage_order', [
            'sumPayPrice'  => $sumPayPrice,
            'shopId'       => $this->shopId,
            'orderId'      => $this->orderId,
            'price'        => $price,
            'percent'      => $percent,
            'brokerage'    => $brokerage,
            'brokeragePer' => $this->brokeragePer,
        ]);

        if (!$isNew) {
            MybankBrokerageService::incShopAllIncomeMonthWithCache($this->shopId, $price);
        }
    }

    public function updataOrder()
    {
        $this->orderInfo->divisionBillId = $this->getDivisionBillId();
        $this->orderInfo->brokeragePer   = $this->getBrokeragePer();
        $this->orderInfo->brokerage      = $this->getBrokerage();
        $this->orderInfo->save();
    }
}
